public without sharing class TechnicalServicesApplicationFormHandler {
    /*
		将技术服务申请中“主题（工作类型）”为“仪器安装”且“审批状态”为“已批准”
		的权限共享给技术服务申请中“客户”的所有人，让此所有人拥有只读权限

    */ 
    public static void shareToSaler(List<TechnicalServicesApplicationForm__c> list_new,Map<Id,TechnicalServicesApplicationForm__c> oldMap ){

    	Id rt = Utils.getRecordTypeIdByDevNameAndObjName('DealerSupportApplication', 'TechnicalServicesApplicationForm__c');
      Id rtLock  = Utils.getRecordTypeIdByDevNameAndObjName('SupportApplicationLocked', 'TechnicalServicesApplicationForm__c');
    	Map<String ,String> townerMap = new Map<String,String>();
    	Map<String,List<String>> accMap = new Map<String,List<String>>();
      Map<Id,Id> caseMap = new Map<Id,Id>();
    	for (TechnicalServicesApplicationForm__c t :list_new ) {
    			TechnicalServicesApplicationForm__c oldT = oldMap.get(t.Id );
    		if(t.Type__c =='安装' && (t.RecordTypeId == rt || t.RecordTypeId== rtLock) && t.Status__c == '已批准' && oldT.Status__c != '已批准' ){

           if(t.Case__c != null && t.MaccuraEngineer__c != null ){
              caseMap.put(t.Case__c, t.MaccuraEngineer__c);
           }
    			if(t.CustomerName__c != null  ){
    				List<String> tmp = new List<String>();
    				if(accMap.containsKey(t.CustomerName__c))tmp.addAll(accMap.get(t.CustomerName__c));
    				tmp.add(t.Id);
    				accMap.put(t.CustomerName__c, tmp);
    				townerMap.put(t.Id, t.OwnerId);

    			}
    		}
    	}
      if(!caseMap.isEmpty())changeEngineer(caseMap);
    	//查找销售员
    	Map<String,String> ownerMap = new Map<String,String>();
    	for (Account acc :[select Id ,OwnerId from Account where Id in: accMap.keySet() and Owner.IsActive = true] ) {
    			
    		ownerMap.put(acc.Id, acc.OwnerId);
    	}

    	//共享权限

    	List<TechnicalServicesApplicationForm__Share> tsList = new List<TechnicalServicesApplicationForm__Share>();
   		for (String accId  :accMap.keySet() ) {
   			
   			for (String tid  : accMap.get(accId)) {
   				if(ownerMap.containsKey(accId) && townerMap.get(tid) != ownerMap.get(accId)){
   					TechnicalServicesApplicationForm__Share ts = new TechnicalServicesApplicationForm__Share();
   					ts.AccessLevel = 'Read';
                	ts.ParentId = tid;
                	ts.UserOrGroupId = ownerMap.get(accId);
                	tsList.add(ts);
   				}
   				
   			}
   		}
   		if(tsList.size() > 0)  insert tsList;

    }

    //当技术服务申请为经销商支援申请 且主题为安装 则去修改关联的服务请求的工程师为 技术服务申请的工程师
    public static void changeEngineer(Map<Id,Id> caseMap){

        List<Case> cList =new List<Case>();
        for (Id cid  : caseMap.keySet()) {
          
             cList.add(new Case(Id=cid ,Engineer__c=caseMap.get(cid) ));
        }
        update cList;
       
    }
}